package com.uduemc.biso.web.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.biso.core.extities.center.Host;
import com.uduemc.biso.core.extities.center.SysServer;
import com.uduemc.biso.core.extities.pojo.NodeTokenForCenter;
import com.uduemc.biso.core.feign.SysServerFeign;
import com.uduemc.biso.core.utils.BisoToken;
import com.uduemc.biso.core.utils.RedisUtil;
import com.uduemc.biso.core.utils.RestResult;

@Component
public class NodeFunction {

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private SysServerFeign sysServerFeign;

	@Autowired
	private ObjectMapper objectMapper;

	public String getRedirectNodeUri(SysServer server, String token) {
		String port = server.getLoginPort();
		String hostName = server.getDomain() + ("80".equals(port) ? "" : ":" + port);
		String url = "http://" + hostName + "/node-login?token=" + token;
		return url;
	}

	/**
	 * 通过 userId 和 host 制作跳转uri，并且token已经存储于redirs中
	 * 
	 * @param userId
	 * @param host
	 * @return
	 */
	public String getRedirectNodeUri(Long userId, Host host, String userType) {
		String token = BisoToken.buildLoginNode(userId, host.getId());
		NodeTokenForCenter value = new NodeTokenForCenter(userId, host.getId(), userType);
		// 通过 host 获取 server 信息
		// 通过 server 信息跳转至对应的次控端带上 token
		SysServer server = null;
		if (host.getServerId() > 0) {
			RestResult restResult = sysServerFeign.findOkOne(host.getServerId());
			if (restResult.getCode() == 200 && restResult.getData() != null) {
				try {
					server = objectMapper.readValue(objectMapper.writeValueAsString(restResult.getData()),
							SysServer.class);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		String url = null;
		if (null != server) {
			redisUtil.set(token, value, 60);
			url = getRedirectNodeUri(server, token);

		}

		return url;
	}

	/**
	 * 通过token到缓存中获取存储的临时数据
	 * 
	 * @param token
	 * @return
	 */
	public NodeTokenForCenter getNodeTokenForCenter(String token) {
		if (!StringUtils.hasText(token)) {
			return null;
		}

		NodeTokenForCenter value = (NodeTokenForCenter) redisUtil.get(token);

		if (value == null) {
			return null;
		}

		redisUtil.del(token);

		return value;
	}

}
